package com.homelink.android.explorerup.component;

import java.io.File;

import com.homelink.android.explorerup.adapter.BaseFileListAdapter;
import com.homelink.android.explorerup.adapter.BaseFileListAdapter.Types;

import android.os.AsyncTask;
import android.util.Log;

public class ReadDirTask extends AsyncTask<String, String, String[]> {
	private String mCurrentPath = "/";
	private BaseFileListAdapter mAdapter;
	public static final String TAG = "ReadDirTask";
	private ReadDirListener mListener;

	public ReadDirTask(BaseFileListAdapter adapter, ReadDirListener listener) {
		mAdapter = adapter;
		mListener = listener;
	}

	public void setCurrentAbsPath(String path) {
		mCurrentPath = path;
		mAdapter.setBasePath(mCurrentPath);
	}

	@Override
	protected String[] doInBackground(String... params) {
		setCurrentAbsPath(params[0]);
		Log.d(TAG, "doInBackground...." + mCurrentPath);
		String[] files = null;
		if (mAdapter.getType() == Types.Simple) {
			files = readSimpleDirs();
		}
		this.publishProgress(files);
		return null;
	}

	protected void onProgressUpdate(String... values) {
		FileDetails[] files = null;
		if (values != null) {
			 files = new FileDetails[values.length];
			for (int i = 0; i < files.length; i++) {
				files[i] = new FileDetails();
				files[i].name = values[i];
				files[i].path = mCurrentPath + File.separator + files[i].name;
			}
			
		}
		mAdapter.setFiles(files);
		if (mListener != null) {
			mListener.onFinished(files);
		}
	}

	/**
	 * if (status.equals(Environment.MEDIA_MOUNTED)) { File path =
	 * Environment.getExternalStorageDirectory(); StatFs statFs = new
	 * StatFs(path.getPath()); long totalBlocks = statFs.getBlockCount(); long
	 * size = statFs.getBlockSize();
	 */

	private String[] readSimpleDirs() {

		File f = new File(mCurrentPath);

		return f.list();
	}

	public static interface ReadDirListener {
		public void onFinished(FileDetails[] files);
	}

}
